package com.zhi.mbtibot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhi.mbtibot.entity.Message;
import com.zhi.mbtibot.mapper.MessageMapper;
import com.zhi.mbtibot.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

/**
 * 功能:Message类的方法实现，CRUD
 * 作者:YukiSu
 * 日期:2024/7/20 20:13
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageMapper messageMapper;


    @Override
    public void addMessage(Message message) {
        log.info(message.toString());
        int rows = messageMapper.insert(message);
        if (rows == 1) {
            System.out.println("添加成功");
        }
        else {
            System.out.println("添加失败");
        }
    }

    @Override
    public void deleteMessage(Integer uid, Integer no) {

        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(Map.of("uid", uid, "no", no));
        int rows = messageMapper.delete(queryWrapper);
        if (rows == 1) {
            System.out.println("删除成功");
        }
        else {
            System.out.println("删除失败");
        }
    }

    @Override
    public void updateMessage(Message message) {

        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(Map.of("uid", message.getUid(), "no", message.getNo()));
        int rows = messageMapper.delete(queryWrapper);
        if (rows == 1) {
            System.out.println("更新成功");
        }
        else {
            System.out.println("更新失败");
        }
    }

    @Override
    public List<Message> getMessageListByUid(Integer uid) {

        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        queryWrapper.orderByAsc("no");
        return messageMapper.selectList(queryWrapper);
    }

    @Override
    public Integer getLastMessageNo(Integer uid) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        String sql = "select MAX(no) from message where uid = " + uid.toString();
        queryWrapper.eqSql("no", sql);
        if (messageMapper.selectOne(queryWrapper) == null) {
            return 0;
        }
        else {
            System.out.println(messageMapper.selectOne(queryWrapper).toString());
            return messageMapper.selectOne(queryWrapper).getNo();
        }
    }

    @Override
    public void deleteMessageListByUid(Integer uid) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid", uid);
        int rows = messageMapper.delete(queryWrapper);
        if (rows == 1) {
            log.info("删除成功");
        }
        else {
            log.info("删除失败");
        }
    }
}